<template>
  <div class="profile-container">
    <div class="profile-header">
      <h1>个人信息</h1>
      <p>管理您的个人资料和账户设置</p>
    </div>
    
    <div class="profile-content">
      <div class="profile-card">
        <h3>基本信息</h3>
        <form @submit.prevent="handleUpdateProfile">
          <div class="form-group">
            <label>姓名</label>
            <input v-model="profileForm.name" type="text" required />
          </div>
          
          <div class="form-group">
            <label>邮箱地址</label>
            <input v-model="profileForm.email" type="email" disabled />
            <span class="help-text">邮箱地址不可修改</span>
          </div>
          
          <button type="submit" :disabled="loading" class="update-btn">
            {{ loading ? '更新中...' : '更新信息' }}
          </button>
        </form>
        
        <div v-if="profileMessage" class="message" :class="{ error: !profileSuccess }">
          {{ profileMessage }}
        </div>
      </div>
      
      <div class="profile-card">
        <h3>修改密码</h3>
        <form @submit.prevent="handleChangePassword">
          <div class="form-group">
            <label>当前密码</label>
            <input v-model="passwordForm.currentPassword" type="password" required />
          </div>
          
          <div class="form-group">
            <label>新密码</label>
            <input v-model="passwordForm.newPassword" type="password" required minlength="6" />
          </div>
          
          <div class="form-group">
            <label>确认新密码</label>
            <input v-model="passwordForm.confirmNewPassword" type="password" required />
          </div>
          
          <button type="submit" :disabled="passwordLoading" class="password-btn">
            {{ passwordLoading ? '修改中...' : '修改密码' }}
          </button>
        </form>
        
        <div v-if="passwordMessage" class="message" :class="{ error: !passwordSuccess }">
          {{ passwordMessage }}
        </div>
      </div>
      
      <div class="profile-card">
        <h3>账户信息</h3>
        <div class="account-info">
          <div class="info-item">
            <span class="label">用户角色：</span>
            <span class="value">{{ userRoleText }}</span>
          </div>
          <div class="info-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ formatDate(authStore.user?.createdAt) }}</span>
          </div>
          <div v-if="!authStore.isAdmin" class="info-item">
            <span class="label">账户余额：</span>
            <span class="value">¥{{ authStore.user?.balance || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="label">账户状态：</span>
            <span class="value status-active">正常</span>
          </div>
        </div>
        
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const profileForm = reactive({
  name: '',
  email: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})

const loading = ref(false)
const passwordLoading = ref(false)
const profileMessage = ref('')
const passwordMessage = ref('')
const profileSuccess = ref(false)
const passwordSuccess = ref(false)

const userRoleText = computed(() => {
  const roles = {
    admin: '管理员',
    user: '普通用户'
  }
  return roles[authStore.user?.role] || '未知'
})

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
  if (authStore.user) {
    profileForm.name = authStore.user.name || ''
    profileForm.email = authStore.user.email || ''
  }
})

const handleUpdateProfile = async () => {
  loading.value = true
  profileMessage.value = ''
  
  try {
    const result = await authStore.updateProfile(profileForm)
    
    if (result.success) {
      profileSuccess.value = true
      profileMessage.value = '个人信息更新成功！'
    } else {
      profileSuccess.value = false
      profileMessage.value = result.message
    }
  } catch (error) {
    profileSuccess.value = false
    profileMessage.value = '更新失败，请重试'
  } finally {
    loading.value = false
  }
}

const handleChangePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmNewPassword) {
    passwordSuccess.value = false
    passwordMessage.value = '两次输入的密码不一致'
    return
  }
  
  if (passwordForm.newPassword.length < 6) {
    passwordSuccess.value = false
    passwordMessage.value = '新密码长度至少6位'
    return
  }
  
  passwordLoading.value = true
  passwordMessage.value = ''
  
  try {
    const result = await authStore.changePassword(passwordForm)
    
    if (result.success) {
      passwordSuccess.value = true
      passwordMessage.value = '密码修改成功！'
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmNewPassword = ''
    } else {
      passwordSuccess.value = false
      passwordMessage.value = result.message
    }
  } catch (error) {
    passwordSuccess.value = false
    passwordMessage.value = '密码修改失败，请重试'
  } finally {
    passwordLoading.value = false
  }
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 40px;
}

.profile-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.profile-header p {
  color: #666;
  font-size: 16px;
}

.profile-content {
  display: grid;
  gap: 30px;
}

.profile-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.profile-card h3 {
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #007bff;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #007bff;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  color: #999;
}

.help-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.update-btn, .password-btn {
  padding: 12px 24px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.update-btn:disabled, .password-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.update-btn:hover:not(:disabled), .password-btn:hover:not(:disabled) {
  background: #0056b3;
}

.logout-btn {
  padding: 12px 24px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  margin-top: 20px;
}

.logout-btn:hover {
  background: #c82333;
}

.account-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #555;
  min-width: 100px;
}

.info-item .value {
  color: #333;
}

.status-active {
  color: #28a745;
  font-weight: 500;
}

.message {
  padding: 10px;
  border-radius: 4px;
  margin-top: 20px;
  text-align: center;
}

.message:not(.error) {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .profile-container {
    padding: 10px;
  }
}
</style>